<!DOCTYPE HTML>
<html lang="en" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>Bracket-Lib Usage Guide</title>
        
        <meta name="robots" content="noindex" />
        
        


        <!-- Custom HTML head -->
        


        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        
        <link rel="icon" href="favicon.svg">
        
        
        <link rel="shortcut icon" href="favicon.png">
        
        <link rel="stylesheet" href="css/variables.css">
        <link rel="stylesheet" href="css/general.css">
        <link rel="stylesheet" href="css/chrome.css">
        
        <link rel="stylesheet" href="css/print.css" media="print">
        

        <!-- Fonts -->
        <link rel="stylesheet" href="FontAwesome/css/font-awesome.css">
        
        <link rel="stylesheet" href="fonts/fonts.css">
        

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="highlight.css">
        <link rel="stylesheet" href="tomorrow-night.css">
        <link rel="stylesheet" href="ayu-highlight.css">

        <!-- Custom theme stylesheets -->
        

        
    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded "><a href="what_is_it.html"><strong aria-hidden="true">1.</strong> What is Bracket-lib</a></li><li class="chapter-item expanded "><a href="linking.html"><strong aria-hidden="true">2.</strong> Quick Start</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="hello_terminal.html"><strong aria-hidden="true">2.1.</strong> Hello Terminal</a></li><li class="chapter-item expanded "><a href="individual_parts.html"><strong aria-hidden="true">2.2.</strong> Using Individual Components</a></li></ol></li><li class="chapter-item expanded "><a href="examples.html"><strong aria-hidden="true">3.</strong> Using the Examples</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="ex_color.html"><strong aria-hidden="true">3.1.</strong> Color Examples</a></li><li class="chapter-item expanded "><a href="ex_geometry.html"><strong aria-hidden="true">3.2.</strong> Geometry Examples</a></li><li class="chapter-item expanded "><a href="ex_noise.html"><strong aria-hidden="true">3.3.</strong> Noise Examples</a></li><li class="chapter-item expanded "><a href="ex_path.html"><strong aria-hidden="true">3.4.</strong> Pathfinding Examples</a></li><li class="chapter-item expanded "><a href="ex_rng.html"><strong aria-hidden="true">3.5.</strong> Random Examples</a></li><li class="chapter-item expanded "><a href="ex_bterm.html"><strong aria-hidden="true">3.6.</strong> Terminal Examples</a></li></ol></li><li class="chapter-item expanded "><a href="consoles.html"><strong aria-hidden="true">4.</strong> Working with Consoles</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="consoles_print.html"><strong aria-hidden="true">4.1.</strong> Printing to Consoles</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                
                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                        
                    </div>

                    <h1 class="menu-title">Bracket-Lib Usage Guide</h1>

                    <div class="right-buttons">
                        
                        <a href="print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>
                        
                        
                    </div>
                </div>

                
                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" name="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>
                

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1><a class="header" href="#what-is-bracket-lib" id="what-is-bracket-lib">What is Bracket-lib</a></h1>
<p><code>bracket-lib</code> started out life as RLTK - The RogueLike Toolkit. Initially, I needed a code-page 437 terminal library on which to build roguelikes. The <a href="http://bfnightly.bracketproductions.com/rustbook/">Rust Roguelike Tutorial</a> grew, and so did the library. Then <a href="https://hands-on-rust.com/">Hands-on Rust</a> (my book about learning Rust) was born, and <code>bracket-lib</code> became the primary library behind the book.</p>
<p>Bracket-lib is intended to fulfill the following needs:</p>
<ul>
<li>A user-friendly <em>teaching</em> library. If I have to choose between performance and a new-user friendly interface, 99% of the time I'll choose the friendly approach.</li>
<li>Provide virtual consoles on a variety of platforms, from the web to major Operating Systems.</li>
<li>Provide a number of extensions to allow you to do layering, sprites, and more advanced rendering---without hurting the overall goal of the library.</li>
<li>Provide a good &quot;on ramp&quot; for moving onto high-performance libraries once you've mastered the basics.</li>
<li>Remain agnostic about how you write your game. ECS, tick methods, embedded scripting---take the path you want. Bracket-lib is meant to provide the basic tools you need and let you unleash your imagination.</li>
</ul>
<p>This &quot;getting started&quot; guide is intended to help you get started with <code>bracket-lib</code>.</p>
<h1><a class="header" href="#linking-to-bracket-lib" id="linking-to-bracket-lib">Linking to Bracket-lib</a></h1>
<p>The quickest and easiest way to use <code>bracket-lib</code> in your program is to include the entire library in your project. Open your project's <code>Cargo.toml</code> and include:</p>
<pre><code class="language-toml">[dependencies]
bracket-lib = &quot;0.8&quot;
</code></pre>
<p>You now have the whole <code>bracket-lib</code> project linked to your program.</p>
<h2><a class="header" href="#using-the-github-version" id="using-the-github-version">Using the Github Version</a></h2>
<p>If you'd like to live on the bleeding edge, you can link to the Github version. In your project's <code>Cargo.toml</code> file, add the following:</p>
<pre><code class="language-toml">[dependencies]
bracket-lib = { git = &quot;https://github.com/amethyst/bracket-lib.git&quot; }
</code></pre>
<p>The main reason to do this is to try out new features. The Github version isn't <em>always</em> as stable as I'd like, so proceed with caution.</p>
<h1><a class="header" href="#hello-terminal" id="hello-terminal">Hello Terminal</a></h1>
<p>You can get to <code>hello terminal</code> pretty quickly:</p>
<h2><a class="header" href="#create-a-new-project" id="create-a-new-project">Create a New Project</a></h2>
<p>Find the directory in which you want to start developing, and type <code>cargo init my_project</code> to create a new project.</p>
<h2><a class="header" href="#link-bracket-lib" id="link-bracket-lib">Link Bracket-Lib</a></h2>
<p>Open <code>Cargo.toml</code> in the newly created project, and expand the <code>[dependencies]</code> section as follows:</p>
<pre><code class="language-toml">[dependencies]
bracket-lib = &quot;0.8&quot;
</code></pre>
<h2><a class="header" href="#hello-minimal-terminal" id="hello-minimal-terminal">Hello Minimal Terminal</a></h2>
<p>The following code prints &quot;Hello Bracket World&quot; in a new simple console:</p>
<pre><pre class="playground"><code class="language-rust">use bracket_lib::prelude::*;

struct State {}

impl GameState for State {
    fn tick(&amp;mut self, ctx: &amp;mut BTerm) {
        ctx.print(1, 1, &quot;Hello Bracket World&quot;);
    }
}

fn main() -&gt; BError {
    let context = BTermBuilder::simple80x50()
        .with_title(&quot;Hello Minimal Bracket World&quot;)
        .build()?;

    let gs: State = State {};
    main_loop(context, gs)
}
</code></pre></pre>
<p>This provides what you need for a minimal start:</p>
<ol>
<li>Importing the <code>prelude</code> from <code>bracket_lib</code> makes the various types and functions available.</li>
<li>You have to create a <code>State</code> object. This is where your ongoing game state is stored.</li>
<li>Implementing <code>GameState</code> provides <code>bracket-lib</code> with a <code>tick</code> function to call on every frame.</li>
<li>Your <code>main</code> function constructs a terminal---in this case an 80x50 text console.</li>
<li>You create a <code>State</code> object, even though it doesn't have much state to store.</li>
<li>Launching <code>main_loop</code> hands control over to <code>bracket-lib</code>, and runs the <code>tick</code> function on every rendered frame.</li>
</ol>
<h2><a class="header" href="#bouncy-hello-world" id="bouncy-hello-world">Bouncy Hello World</a></h2>
<p>Another example (<code>hello_terminal</code> in the <code>bracket-lib</code> source) provides a bouncing &quot;Hello World&quot;. Let's use it to explore some of the features available in the library:</p>
<pre><pre class="playground"><code class="language-rust">use bracket_lib::prelude::*;

struct State {
    y: i32,
    going_down: bool,
}

impl GameState for State {
    fn tick(&amp;mut self, ctx: &amp;mut BTerm) {
        let col1 = RGB::named(CYAN);
        let col2 = RGB::named(YELLOW);
        let percent: f32 = self.y as f32 / 50.0;
        let fg = col1.lerp(col2, percent);

        ctx.cls();
        ctx.printer(
            40,
            49,
            &quot;#[blue]Hello #[pink]Bracket#[] world.&quot;,
            TextAlign::Center,
            Some(RGBA::from_u8(200, 200, 200, 255)),
        );

        ctx.print_color(
            1,
            self.y,
            fg,
            RGB::named(BLACK),
            &quot;♫ ♪ Hello Bracket World ☺&quot;,
        );

        if self.going_down {
            self.y += 1;
            if self.y &gt; 48 {
                self.going_down = false;
            }
        } else {
            self.y -= 1;
            if self.y &lt; 2 {
                self.going_down = true;
            }
        }

        ctx.draw_box(39, 0, 20, 3, RGB::named(WHITE), RGB::named(BLACK));
        ctx.printer(
            58,
            1,
            &amp;format!(&quot;#[pink]FPS: #[]{}&quot;, ctx.fps),
            TextAlign::Right,
            None,
        );
        ctx.printer(
            58,
            2,
            &amp;format!(&quot;#[pink]Frame Time: #[]{} ms&quot;, ctx.frame_time_ms),
            TextAlign::Right,
            None,
        );
    }
}

fn main() -&gt; BError {
    let context = BTermBuilder::simple80x50()
        .with_title(&quot;Hello Bracket World&quot;)
        .build()?;

    let gs: State = State {
        y: 1,
        going_down: true,
    };

    register_palette_color(&quot;blue&quot;, RGB::named(BLUE));
    register_palette_color(&quot;pink&quot;, RGB::named(MAGENTA));

    main_loop(context, gs)
}
</code></pre></pre>
<p>There's quite a lot to unwrap here, so let's go through a quick tour of using <code>bracket-lib</code>.</p>
<h3><a class="header" href="#the-state-structure" id="the-state-structure">The State Structure</a></h3>
<p>Everything your program needs to retain during execution lives in your state structure (well, you could use globals and lazy-statics). In this case, we're storing two variables in <code>State</code>:</p>
<ul>
<li><code>y</code> stores the current vertical location of the bouncing &quot;Hello Bracket World&quot;.</li>
<li><code>going_down</code> stores whether the words are going up or down at the moment. It changes direction at the top and bottom of the screen.</li>
</ul>
<h3><a class="header" href="#setup" id="setup">Setup</a></h3>
<p>In the <code>main</code> function, we start by initializing <code>bracket-terminal</code>. We ask for a simple 80x50 console, and title the window. The <code>build()</code> function actually creates the window; the other chained functions return an object <em>describing</em> what you want. There's a lot of options you can choose, documented elsewhere in this guide.</p>
<p>We initialize <code>State</code> with some starting values for the bouncing text. Then we call <code>register_palette_color</code>---more on that in &quot;pretty printing&quot;, below. Finally, we call <code>main_loop</code> to begin running the program---and calling <code>tick</code> every frame.</p>
<h3><a class="header" href="#printing-to-the-console" id="printing-to-the-console">Printing to the Console</a></h3>
<ol>
<li>The <code>tick</code> function starts by defining some colors. The <code>RGB::named(xxx)</code> functions return a color object. The library defines all of the W3C named colors; you can also use <code>from_rgb</code> to specify one yourself. These colors are then used in various printing functions.</li>
<li>Then it does a little dance to figure out where to draw the bouncing hello world.</li>
<li><code>ctx.cls()</code> clears the console.</li>
<li><code>ctx.printer</code> is then used to &quot;pretty print&quot; the words &quot;Hello Bracket World&quot;. 
<ol>
<li>The decorators <code>#[blue]</code>, <code>#[pink]</code> specify that text following that marker should be in the color that was registered wih the <code>register_palette_color</code> label.</li>
<li>The two numbers (40, 49) are screen coordinates.</li>
<li><code>TextAlign::center</code> will center the text horizontally around the specified coordinates.</li>
<li><code>Some(RGBA::from_u8(200, 200, 200, 255))</code> describes a background color for the text.</li>
</ol>
</li>
<li>Then we use the <code>print_color</code> commands, which is a simpler way to put single-color text on the console.</li>
<li>Some more <code>printer</code> calls, demonstrating different alignments and color settings.</li>
</ol>
<p>Notice that in the text, we use unicode. <code>♫ ♪ Hello Bracket World ☺</code> is valid, because the characters are part of the codepage-437 set---and <code>bracket-terminal</code> automatically translates them.</p>
<p>You'll find more detailed usage instructions throughout this document.</p>
<h1><a class="header" href="#using-individual-bracket-lib-components" id="using-individual-bracket-lib-components">Using Individual Bracket-Lib Components</a></h1>
<p><code>bracket-lib</code> is a collection of libraries. You can depend upon them individually, if you only want part of the <code>bracket-lib</code> functionality. The parts are:</p>
<ul>
<li><code>bracket-algorithm-traits</code> defines some traits that are used in other parts of the program.</li>
<li><code>bracket-color</code> defines how the library handles color, and includes functions for grayscale, RGB/RGBA/HSV conversion, a lot of named colors, and general color management support.</li>
<li><code>bracket-geometry</code> provides points, lines, rectangles and circle support.</li>
<li><code>bracket-noise</code> provides Perlin, Simplex, White and other noise functions useful for randomly generating things.</li>
<li><code>bracket-pathfinding</code> provides an A-Star and a Dijkstra mapping solution.</li>
<li><code>bracket-random</code> provides an easy-to-use wrapper to a random number generator.</li>
<li><code>bracket-terminal</code> provides console rendering and support.</li>
</ul>
<p>When you link directly to a dependency, the namespace is on longer <code>bracket_lib::prelude</code>. Instead, it will be the crate's name, e.g. <code>bracket_random::prelude</code>.</p>
<p>This option is partly provided to help keep development efforts separated, and partly because sometimes you just want a small portion of what the library has to offer---and there's no point in wasting space (and mostly compile time) on the bits you don't need.</p>
<h1><a class="header" href="#using-the-examples" id="using-the-examples">Using the Examples</a></h1>
<p>Each of the <code>bracket-lib</code> crates comes with a number of examples. These are a great source of inspiration for how the parts of the library fit together, as well as serving as a demonstration of what can be done.</p>
<p>You can run examples locally by changing directory to the crate you wish to use (e.g. <code>cd bracket-terminal</code>), and then running <code>cargo run --example (name)</code>. You can get a list of valid example names by omitting <code>(name)</code>.</p>
<blockquote>
<p>Many people find they learn better by reading examples, rather than big manuals. If so, this section is for you!</p>
</blockquote>
<h2><a class="header" href="#bracket-color-examples" id="bracket-color-examples">Bracket-Color Examples</a></h2>
<p>All of the <code>bracket-color</code> examples require <code>crossterm</code> for console output. You can run them with:</p>
<pre><code>cd bracket-color
cargo run --example (name) --no-default-features --features crossterm
</code></pre>
<h3><a class="header" href="#colors" id="colors">colors</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-color/examples/colors.rs">Source Code</a>.</p>
<p>The <code>colors</code> example demonstrates printing to the console in a number of colors, demonstrating several of the ways in which colors can be generated (named, from floating point and byte RGB).</p>
<p><img src="./ex_col_colors.jpg" alt="" /></p>
<h3><a class="header" href="#lerp" id="lerp">lerp</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-color/examples/lerp.rs">Source Code</a></p>
<p>The <code>lerp</code> example shows how to use the <code>lerp</code> function, providing smooth transitions between two colors. The transition occurs in the RGB space. You can use HSV colors to lerp in that space if you wish. (&quot;Lerp&quot; is a common shorthand for &quot;Linear Interpolation&quot;)</p>
<p><img src="./ex_col_lerp.jpg" alt="" /></p>
<h3><a class="header" href="#lerpit" id="lerpit">lerpit</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-color/examples/lerpit.rs">Source Code</a></p>
<p>Similar to the <code>lerp</code> example, but using an iterator instead of repeated calls to the <code>lerp</code> function. <code>Bracket-color</code> includes an <code>RgbLerp</code> iterator for this purpose.</p>
<p><img src="./ex_col_lerpit.jpg" alt="" /></p>
<h3><a class="header" href="#lerpit_hsv" id="lerpit_hsv">lerpit_hsv</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-color/examples/lerpit_hsv.rs">Source Code</a></p>
<p>This is just like the <code>lerpit</code> example, but using an HSV color space for interpolation via the <code>HsvLerp</code> iterator.</p>
<p><img src="./ex_col_lerpit_hsv.jpg" alt="" /></p>
<h3><a class="header" href="#named_color" id="named_color">named_color</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-color/examples/named_color.rs">Source Code</a></p>
<p>A very simple demo printing colors obtained via <code>RGB::named</code>, including a quick test of the <code>into</code> conversion between colors.</p>
<p><img src="./ex_col_named.jpg" alt="" /></p>
<h3><a class="header" href="#shades_of_grey" id="shades_of_grey">shades_of_grey</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-color/examples/shades_of_grey.rs">Source Code</a></p>
<p>This demo shows off how to use <code>to_greyscale()</code> and <code>desaturate()</code> on colors, providing two different methods of converting colors to greyscale.</p>
<p><img src="./ex_col_shades_of_grey.jpg" alt="" /></p>
<h2><a class="header" href="#bracket-geometry-examples" id="bracket-geometry-examples">Bracket-Geometry Examples</a></h2>
<h3><a class="header" href="#bresenham_circle" id="bresenham_circle">bresenham_circle</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/tree/master/bracket-geometry/examples">Source Code</a></p>
<p>This demonstrates the use of <code>BresenhamCircle</code> to plot gridded circles, quickly and with compensation for grid locations.</p>
<p><img src="./ex_geom_circle.jpg" alt="" /></p>
<h3><a class="header" href="#bresenham_line" id="bresenham_line">bresenham_line</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-geometry/examples/bresenham_line.rs">Source Code</a></p>
<p>This example draws a line and plots it on the console, using Bresenham's Line algorithm.</p>
<p><img src="./ex_geom_bline.jpg" alt="" /></p>
<h3><a class="header" href="#bresenham_sweep" id="bresenham_sweep">bresenham_sweep</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-geometry/examples/bresenham_sweep.rs">Source Code</a></p>
<p>This example sweeps from 0 to 360 degrees, using <code>bracket-geometry</code> angle functions. It then projects a point along that angle, and draws a Bresenham Line to the new point.</p>
<p><img src="./ex_geom_bsweep.gif" alt="" /></p>
<h3><a class="header" href="#distance" id="distance">distance</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-geometry/examples/distance.rs">Source Code</a></p>
<p>This example calculates the distance between two points using Pythagoras, Pythagoras Squared, Manhattan and Chebyshev distance algorithms.</p>
<pre><code>Given the two points:
Point {
    x: 0,
    y: 0,
}
Point {
    x: 10,
    y: 20,
}

Pythagoras Distance: 22.36068
Pythagoras Squared Distance: 500
Manhattan Distance: 30
Chebyshev Distance: 20
</code></pre>
<h3><a class="header" href="#vector_line" id="vector_line">vector_line</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-geometry/examples/vector_line.rs">Source Code</a></p>
<p>This example uses vector math to plot a line, rather than Bresenham. It can be slightly faster on some CPUs, if you are plotting enough lines (or long enough lines) for the floating-point math to make a difference. Lines aren't quite as nice as their Bresenham brethren.</p>
<pre><code>..........
.*........
..*.......
..**......
...*......
....*.....
.....*....
.....**...
......*...
.......*..
</code></pre>
<h2><a class="header" href="#bracket-noise-examples" id="bracket-noise-examples">Bracket-Noise Examples</a></h2>
<h3><a class="header" href="#cellular" id="cellular">cellular</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-noise/examples/cellular.rs">Source Code</a></p>
<p>Note that this is <em>not</em> cellular automata! Generates <em>cellular</em> noise, basically a randomized Voronoi pattern.</p>
<p><img src="./ex_noise_cellular.jpg" alt="" /></p>
<h3><a class="header" href="#perlin_fractal" id="perlin_fractal">perlin_fractal</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-noise/examples/perlin_fractal.rs">Source Code</a></p>
<p>This example uses Perlin Fractal Noise to generate an ASCII height map.</p>
<p><img src="./ex_noise_perlin_fractal.jpg" alt="" /></p>
<h3><a class="header" href="#simplex_billow_quintic" id="simplex_billow_quintic">simplex_billow_quintic</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-noise/examples/simplex_billow_quintic.rs">Source Code</a></p>
<p>This examples uses Simplex noise to make a heightmap, using the Billow and Quintic modes.</p>
<p><img src="./ex_noise_simplex_billow.jpg" alt="" /></p>
<h3><a class="header" href="#simplex_fractal" id="simplex_fractal">simplex_fractal</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-noise/examples/simplex_fractal.rs">Source Code</a></p>
<p>This example uses Simplex noise in Fractal mode to make a heightmap.</p>
<p><img src="./ex_noise_simplex_fractal.jpg" alt="" /></p>
<h3><a class="header" href="#simplex_rigid_hermite" id="simplex_rigid_hermite">simplex_rigid_hermite</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-noise/examples/simplex_rigid_hermite.rs">Source Code</a></p>
<p>This example uses Simplex noise in Rigit Hermite mode to make a heightmap.</p>
<p><img src="./ex_noise_simplex_rigid.jpg" alt="" /></p>
<h3><a class="header" href="#value" id="value">value</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-noise/examples/value.rs">Source Code</a></p>
<p>This example uses value noise for simple interpolation.</p>
<p><img src="./ex_noise_value.jpg" alt="" /></p>
<h3><a class="header" href="#value_fractal" id="value_fractal">value_fractal</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-noise/examples/value_fractal.rs">Source Code</a></p>
<p>This example uses value noise in fractal interpolation mode.</p>
<p><img src="./ex_noise_value_fractal.jpg" alt="" /></p>
<h3><a class="header" href="#whitenosie" id="whitenosie">whitenosie</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-noise/examples/whitenoise.rs">Source Code</a></p>
<p>Generates a really random looking field of white noise. Perfect for snow, or for feeding random data to a shader.</p>
<p><img src="./ex_noise_white.jpg" alt="" /></p>
<h2><a class="header" href="#bracket-pathfinding-examples" id="bracket-pathfinding-examples">Bracket-Pathfinding Examples</a></h2>
<h3><a class="header" href="#astar" id="astar">astar</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/tree/master/bracket-pathfinding/examples/astar">Source Code</a></p>
<p>A quick demonstration of A-star pathfinding in action. Demonstrates the minimum required for accurate A-star pathing.</p>
<p><img src="./ex_path_astar.jpg" alt="" /></p>
<h3><a class="header" href="#astar_manhattan" id="astar_manhattan">astar_manhattan</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/tree/master/bracket-pathfinding/examples/astar_manhattan">Source Code</a></p>
<p>Demonstrates using Manhattan distances in A-Star, rather than regular Pythagoras.</p>
<p><img src="./ex_path_astar_manhattan.jpg" alt="" /></p>
<h3><a class="header" href="#dijkstra" id="dijkstra">dijkstra</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/tree/master/bracket-pathfinding/examples/dijkstra">Source Code</a></p>
<p>Demonstrates the usage of the Dijkstra maps feature by brightening areas close to starting points, and darkening those further away.</p>
<p><img src="./ex_path_dijkstra.jpg" alt="" /></p>
<h3><a class="header" href="#fov" id="fov">fov</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/tree/master/bracket-pathfinding/examples/fov">Source Code</a></p>
<p>Demonstrates the Field-of-View functionality.</p>
<p><img src="./ex_path_fov.jpg" alt="" /></p>
<h2><a class="header" href="#bracket-random-examples" id="bracket-random-examples">Bracket-Random Examples</a></h2>
<h3><a class="header" href="#diceroll" id="diceroll">diceroll</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-random/examples/diceroll.rs">Source Code</a></p>
<p>Demonstrates using the <code>roll_dice</code> functionality of the RNG to roll dice in a familiar, RPG-style. <code>3d6</code> is represented as <code>roll_dice(3, 6)</code>.</p>
<pre><code>Rolling 3d6, 10 times.
3d6 Roll: 10
3d6 Roll: 8
3d6 Roll: 11
3d6 Roll: 10
3d6 Roll: 14
3d6 Roll: 7
3d6 Roll: 13
3d6 Roll: 9
3d6 Roll: 13
3d6 Roll: 11
Total of rolls: 106
</code></pre>
<h3><a class="header" href="#dicestring" id="dicestring">dicestring</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-random/examples/dicestring.rs">Source Code</a></p>
<p>Demonstrates using the <code>roll_str</code> functionality to allow you to enter dice types as strings. For example, <code>roll_str(&quot;3d6&quot;)</code>. Note that this is a lot slower due to parsing requirements.</p>
<pre><code>Rolling 3d6, 10 times.
3d6 Roll: 13
3d6 Roll: 3
3d6 Roll: 11
3d6 Roll: 6
3d6 Roll: 8
3d6 Roll: 12
3d6 Roll: 5
3d6 Roll: 10
3d6 Roll: 12
3d6 Roll: 13
Total of rolls: 93
</code></pre>
<h3><a class="header" href="#die_iterator" id="die_iterator">die_iterator</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-random/examples/die_iterator.rs">Source Code</a></p>
<p>Creates a dice iterator, each rolling a 6-sided die. Takes 10 dice rolls and prints them.</p>
<pre><code>Rolled 3
Rolled 1
Rolled 3
Rolled 6
Rolled 2
Rolled 4
Rolled 1
Rolled 2
Rolled 1
Rolled 1
</code></pre>
<h3><a class="header" href="#distribution" id="distribution">distribution</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-random/examples/distribution.rs">Source Code</a></p>
<p>Rolls a lot of dice and plots their relative distribution. This is intended to validate that the random number generator is behaving appropriately.</p>
<pre><code>Rolling 3d6, 200000 times and counting distribution.
03 : ##
04 : #######
05 : ###############
06 : #########################
07 : ######################################
08 : #####################################################
09 : ################################################################
10 : ####################################################################
11 : ######################################################################
12 : #################################################################
13 : #####################################################
14 : ######################################
15 : ##########################
16 : ###############
17 : #######
18 : ##
</code></pre>
<h3><a class="header" href="#next" id="next">next</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-random/examples/next.rs">Source Code</a></p>
<p>Demonstrates the <code>next_u64</code> function in the RNG, which passes straight through to the underlying RNG code.</p>
<pre><code>Generating the next 10 u64 numbers
Roll: 18130881974873676332
Roll: 3148465433356529749
Roll: 44531299326498369
Roll: 9665219486649819621
Roll: 10520437451657888625
Roll: 12316016225926642867
Roll: 2116667603649678054
Roll: 11573604930291377796
Roll: 2541210746452578386
Roll: 17238031251593215327
</code></pre>
<h3><a class="header" href="#rand" id="rand">rand</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-random/examples/rand.rs">Source Code</a></p>
<p>Demonstrates how to use <code>rand</code> to generate a random number of a specified type.</p>
<pre><code>Generating the next 10 f64 numbers
Roll: 0.7195672608676137
Roll: 0.5348780904141426
Roll: 0.8706676996760022
Roll: 0.32794462603290664
Roll: 0.619775940285832
Roll: 0.4395722002981868
Roll: 0.37184757519241163
Roll: 0.9221657800105313
Roll: 0.35612926854806837
Roll: 0.17372920791278967
</code></pre>
<h3><a class="header" href="#range" id="range">range</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-random/examples/range.rs">Source Code</a></p>
<p>Demonstrates the <code>rng.range(min, max)</code> function.</p>
<pre><code>Generating the next 10 numbers in the range 100 - 200
Roll: 181
Roll: 179
Roll: 199
Roll: 180
Roll: 114
Roll: 117
Roll: 166
Roll: 162
Roll: 196
Roll: 113
</code></pre>
<h3><a class="header" href="#slice" id="slice">slice</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-random/examples/slice.rs">Source Code</a></p>
<p>Demonstrates using the crate to randomly select an entry from a slice (collection) of entries.</p>
<pre><code>Randomly chose a: Cat
Randomly chose a: Dragon
Randomly chose a: Hamster
Randomly chose a: Dragon
Randomly chose a: Cat
Randomly chose a: Dragon
Randomly chose a: Cat
Randomly chose a: Hamster
Randomly chose a: Cat
Randomly chose a: Cat
</code></pre>
<h3><a class="header" href="#slice_index" id="slice_index">slice_index</a></h3>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-random/examples/slice_index.rs">Source Code</a></p>
<p>Demonstrates using <code>slice_index</code> to randomly pull an index entry from a slice of data.</p>
<pre><code>Randomly chose index: 2, which is a Gerbil
Randomly chose index: 0, which is a Cat
Randomly chose index: 0, which is a Cat
Randomly chose index: 1, which is a Dog
Randomly chose index: 0, which is a Cat
Randomly chose index: 2, which is a Gerbil
Randomly chose index: 4, which is a Dragon
Randomly chose index: 4, which is a Dragon
Randomly chose index: 4, which is a Dragon
Randomly chose index: 1, which is a Dog
</code></pre>
<h1><a class="header" href="#terminal-examples" id="terminal-examples">Terminal Examples</a></h1>
<h2><a class="header" href="#alpha" id="alpha">alpha</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/alpha.rs">Source Code</a></p>
<p>Demonstrates the RGBA capabilities of the library, when alpha blending is enabled on a sparse console overlaying a simple console. Also uses the <code>VirtualConsole</code> feature to create a large psuedo-console containing a chunk of <em>A Tale of Two Cities</em>, and rendering that as the base layer.</p>
<p><img src="./ex_bt_alpha.gif" alt="" /></p>
<h2><a class="header" href="#astar_mouse" id="astar_mouse">astar_mouse</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/astar_mouse.rs">Source Code</a></p>
<p>Generates a random blob map, and places a player on it. The player moves to wherever the mouse is clicked, using A star pathfinding. Also generates real-time field of view for the player as they zip around.</p>
<p><img src="./ex_bt_astar_mouse.gif" alt="" /></p>
<h2><a class="header" href="#bench_scalable" id="bench_scalable">bench_scalable</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/bench_scalable.rs">Source Code</a></p>
<p>Generates a completely random console, as fast as possible. Uses the resizable console option to allow the window to be resized while it runs, and queries the console for dimensions---filling as much of it as possible.</p>
<p>No screenshot, sorry.</p>
<h2><a class="header" href="#benchmark" id="benchmark">benchmark</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/benchmark.rs">Source Code</a></p>
<p>Draws a random console as fast as possible. No resizing.</p>
<h2><a class="header" href="#colorfont" id="colorfont">colorfont</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/colorfont.rs">Source Code</a></p>
<p>Demonstrates that you can use color in your font graphic if you want to.</p>
<p><img src="./ex_bt_colorfont.jpg" alt="" /></p>
<h2><a class="header" href="#dwarfmap" id="dwarfmap">dwarfmap</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/dwarfmap.rs">Source Code</a></p>
<p>An homage to <em>Dwarf Fortress</em>. Generates a 3D map, and then renders it top-down with darkening for lower than the player z-levels. Implements a-star pathing in 3D, and mouse-based navigation.</p>
<p><img src="./ex_bt_dwarfmap.gif" alt="" /></p>
<h2><a class="header" href="#flexible" id="flexible">flexible</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/flexible.rs">Source Code</a></p>
<p>Demonstrates using a fancy/flexible console to make a spinning <code>@</code> bounce around the screen.</p>
<p><img src="./ex_bt_flex.gif" alt="" /></p>
<h2><a class="header" href="#fontswitch" id="fontswitch">fontswitch</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/fontswitch.rs">Source Code</a></p>
<p>Demonstrates switching fonts at run-time.</p>
<p><img src="./ex_bt_fontswitch.gif" alt="" /></p>
<h2><a class="header" href="#hello_minimal" id="hello_minimal">hello_minimal</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/hello_minimal.rs">Source Code</a></p>
<p>Minimal hello world, see the quick start guide.</p>
<h2><a class="header" href="#hello_terminal" id="hello_terminal">hello_terminal</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/hello_terminal.rs">Source Code</a></p>
<p>See the quick start guide---a bouncing hello world.</p>
<p><img src="./ex_bt_hello_terminal.gif" alt="" /></p>
<h2><a class="header" href="#input_harness" id="input_harness">input_harness</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/input_harness.rs">Source Code</a></p>
<p>A handy tool to display the key code and mouse information about keys/mouse as they are utilized. Also demonstrates the <code>advanced_input</code> system, providing inputs as a stream of events rather than a simple set.</p>
<p><img src="./ex_bt_input_harness.jpg" alt="" /></p>
<h2><a class="header" href="#keyboard" id="keyboard">keyboard</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/keyboard.rs">Source Code</a></p>
<p>Mostly a debugging tool. Demonstrates keys and their various modifier combiantions.</p>
<h2><a class="header" href="#native_gl" id="native_gl">native_gl</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/native_gl.rs">Source Code</a></p>
<p>Demonstrates how to access the underlying OpenGL system, if you should need it. Note that if you really want to write a GL application, this is a really inefficient way to do it---but it gets you started, and offers a way to perform quick OpenGL calls if you just need something fancy.</p>
<p><img src="./ex_bt_native_gl.jpg" alt="" /></p>
<h2><a class="header" href="#no_cls" id="no_cls">no_cls</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/no_cls.rs">Source Code</a></p>
<p>Mostly a debugging tool, this example shows that consoles accumulate data if you don't call <code>cls</code>. This was important for debugging the native console implementations and their dirty-render detection.</p>
<h2><a class="header" href="#post_process" id="post_process">post_process</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/postprocess.rs">Source Code</a></p>
<p>Demonstrates reading a REX Paint file (.xp), and rendering it to the screen. Enables or disables the terminal's post-processing options, screen-burn and uses scan-lines.</p>
<p><img src="./ex_bt_post.jpg" alt="" /></p>
<h2><a class="header" href="#return_error" id="return_error">return_error</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/return_error.rs">Source Code</a></p>
<p>Demonstrates how to return and act on errors from initialization, should you wish to do so.</p>
<h2><a class="header" href="#rex" id="rex">rex</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/rex.rs">Source Code</a></p>
<p>Loads Nyan Cat from an embedded REX Paint file, and renders it to the screen.</p>
<p><img src="./ex_bt_rex.jpg" alt="" /></p>
<h2><a class="header" href="#sparse" id="sparse">sparse</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/sparse.rs">Source Code</a></p>
<p>Demonstrates layering a sparse console on top of a simple console, with different fonts on each.</p>
<p><img src="./ex_bt_sparse.jpg" alt="" /></p>
<h2><a class="header" href="#sparse_cls" id="sparse_cls">sparse_cls</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/sparse_cls.rs">Source Code</a></p>
<p>Debugging tool, designed to help me notice when I break clearing sparse consoles again!</p>
<h2><a class="header" href="#sprites" id="sprites">sprites</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/sprites.rs">Source Code</a></p>
<p>Uses the sprite layer type (in its infancy) to animate some sprites as they run around the screen.</p>
<p><img src="./ex_bt_sprites.gif" alt="" /></p>
<h2><a class="header" href="#squishy" id="squishy">squishy</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/squishy.rs">Source Code</a></p>
<p>A benchmark tool that also demonstrates the ability to &quot;squish&quot; terminals by dynamically resizing the size of each tile.</p>
<h2><a class="header" href="#textblock" id="textblock">textblock</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/textblock.rs">Source Code</a></p>
<p>Demonstrates the text-block tool, and how it can help with large amounts of text.</p>
<p><img src="./ex_bt_textblock.jpg" alt="" /></p>
<h2><a class="header" href="#textsprites" id="textsprites">textsprites</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/textsprites.rs">Source Code</a></p>
<p>Demonstrates the &quot;multi-tile text sprite&quot; system. You can batch some characters together for quick rendering.</p>
<p><img src="./ex_bt_textsprites.gif" alt="" /></p>
<h2><a class="header" href="#tiles" id="tiles">tiles</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/tiles.rs">Source Code</a></p>
<p>Uses graphical fonts instead of ASCII/CP437 for a visual dungeon experience.</p>
<p><img src="./ex_bt_tiles.jpg" alt="" /></p>
<h2><a class="header" href="#unicode" id="unicode">unicode</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/unicode.rs">Source Code</a></p>
<p>Demonstrates that if you <em>really</em> want to (it's slow!), you can load a giant font containing lots of unicode and display multi-lingual terminals. Run this one in <code>release</code> mode. It takes far too long to start, otherwise.</p>
<p><img src="./ex_bt_unicode.jpg" alt="" /></p>
<h2><a class="header" href="#virtual_console" id="virtual_console">virtual_console</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/virtual_console.rs">Source Code</a></p>
<p>Demonstrates using a virtual console to hold a lot of data, and then displaying windows into the virtual console. This can be handy for logs, manuals and similar. <em>This should have a seizure warning</em></p>
<p><img src="./ex_bt_virtual_console.jpg" alt="" /></p>
<h2><a class="header" href="#walking" id="walking">walking</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/walking.rs">Source Code</a></p>
<p>Demonstrates walking around a map.</p>
<h2><a class="header" href="#walking_with_is_pressed" id="walking_with_is_pressed">walking_with_is_pressed</a></h2>
<p><a href="https://github.com/amethyst/bracket-lib/blob/master/bracket-terminal/examples/walking_with_is_pressed.rs">Source Code</a></p>
<p>The same walking demo, but using the <code>is_pressed</code> function (for advanced input) rather than the simple key enum.</p>
<h1><a class="header" href="#working-with-consoles" id="working-with-consoles">Working with Consoles</a></h1>
<p><code>Bracket-terminal</code> is based around <em>consoles</em>. At its base, a console represents a grid. Consoles have a grid dimension, and each cell/tile is addressed through <code>x</code> and <code>y</code> coordinates:</p>
<table><thead><tr><th></th><th></th><th></th><th></th><th></th></tr></thead><tbody>
<tr><td>0,0</td><td>1,0</td><td>2,0</td><td>3,0</td><td>4,0</td></tr>
<tr><td>0,1</td><td>1,1</td><td>2,1</td><td>3,1</td><td>4,1</td></tr>
<tr><td>0,2</td><td>1,2</td><td>2,2</td><td>3,2</td><td>4,2</td></tr>
<tr><td>0,3</td><td>1,3</td><td>2,3</td><td>3,3</td><td>4,3</td></tr>
<tr><td>0,4</td><td>1,4</td><td>2,4</td><td>3,4</td><td>4,4</td></tr>
</tbody></table>
<p><em>The coordinates extend out to the limits of the console's dimensions.</em></p>
<h2><a class="header" href="#types-of-console" id="types-of-console">Types of Console</a></h2>
<p><code>Bracket-terminal</code> includes the following types of console:</p>
<ul>
<li><strong>Simple Consoles</strong> store an internal vector, representing each tile of the grid. Each tile/cell is rendered as part of an overall grid structure. Simple consoles are best suited to layers that address a large part of the screen.
<ul>
<li>Simple Consoles may or may not contain a background. If they don't include a background, they don't overwrite content behind them.</li>
</ul>
</li>
<li><strong>Sparse Consoles</strong> store a list of characters to render, and the address at which they are rendered. They are best used when you only want to draw a few things on the screen, typically with a simple console behind them.</li>
<li><strong>Fancy Consoles</strong> also store a render list, but add niceties such as fractional coordinates and rotation to characters.</li>
<li><strong>Sprite Consoles</strong> store a list of sprites from a sprite sheet, and render them in <em>pixel</em> coordinates.</li>
<li><strong>Virtual Consoles</strong> aren't rendered, but can store huge amounts of data. Windowing functions make it easy to render parts of the console to another console type. These are great for large blobs of documentation, log files and similar.</li>
</ul>
<h2><a class="header" href="#layers" id="layers">Layers</a></h2>
<p><code>Bracket-terminal</code> supports <em>layering</em>. You can have multiple consoles, drawn on top of one another. Consoles can have their own tile sizes, and may be offset or scaled. They are rendered in the order in which they are initialized---the first console is always rendered first, subsequent consoles are rendered on top of them.</p>
<p>You can use layers to render your game with one tileset, characters with another, and HUD/game information in an attractive text font on top of them all.</p>
<h2><a class="header" href="#initializing-consoles-and-layers" id="initializing-consoles-and-layers">Initializing Consoles and Layers</a></h2>
<p>In your <code>main</code> function, when you initialize <code>bracket-terminal</code> you specify the consoles you require. The simplest possible initialization provides you with a single <em>simple</em> layer, containing 80 (width) by 50 (height) cells:</p>
<pre><pre class="playground"><code class="language-rust">fn main() -&gt; BError {
    let context = BTermBuilder::simple80x50()
        .with_title(&quot;Hello Minimal Bracket World&quot;)
        .build()?;
</code></pre></pre>
<p>Let's have a look at how this works.</p>
<h3><a class="header" href="#constructor" id="constructor">Constructor</a></h3>
<p>So what's really happening here? <code>BTermBuilder</code> is a <em>builder</em> structure that represents what you'd like to construct. You have to start with a constructor. You have some choices:</p>
<ul>
<li>The <code>default</code>, <code>new</code> default to an 80x50 console, but don't specify any details.</li>
<li>The <code>simple80x50</code> constructor provides everything you need for a default, 8x8 font 80x50 console.</li>
<li>The <code>simple(width, height)</code> constructor provides everything you need for a default, 8x8 font <code>width</code> by <code>height</code> console.</li>
<li>The <code>vga80x50</code> constructor initializes an 80x50 console, with a VGA 8x16 font registered.</li>
<li>The <code>vga(width, height)</code> constructor provides a VGA 8x16 font console in the specified dimensions.</li>
</ul>
<p>The <em>constructor</em> provides a starting-point for constructing the console. Chances are, you want to specify more information. The constructor does not return a usable context, yet---it provides a builder that lets you add detail to your request.</p>
<h3><a class="header" href="#global-builder-options" id="global-builder-options">Global Builder Options</a></h3>
<p>Some builder functions provide global (whole program) functionality. These include:</p>
<ul>
<li><code>with_title(string)</code> lets you specify a window title.</li>
<li><code>with_resource_path(string)</code> lets you specify where your font files are saved.</li>
<li><code>with_font(filename, character width, character height)</code> lets you register your own font file.</li>
<li><code>with_font_bg(filename, character width, character height, color)</code> lets you register a font with an explicit background color that will be converted to transparent.</li>
<li><code>with_vsync(bool)</code> lets you turn vertical refresh sync on or off. This uncaps your frame rate, but may lead to visual tearing on some systems.</li>
<li><code>with_fullscreen(bool)</code> lets you specify that the game should try and run in full screen mode, as opposed to a window.</li>
<li><code>with_fps_cap(fps)</code> lets you cap the maximum frames per second at which the game will render, explicitly sleeping to keep CPU load manageable.</li>
<li><code>with_platform_specific(hint)</code> is used for those times you need to tell a renderer something, but that feature can't work in all render targets. These will be documented in the render targets.</li>
<li><code>with_advanced_input(bool)</code> lets you change the input mechanism from populating the key/mouse variables to a stream of keyboard/mouse events.</li>
<li><code>with_automatic_console_resize(bool)</code> lets you change the behavior of resizing the window. Instead of scaling the console up or down to fit the window, a resize event re-calculates the size of the consoles and expands/shrinks them to fit. You can query the current size of a layer from the context in <code>tick</code>.</li>
</ul>
<p>These provide a fair amount of control over the general program. If you want to use layers, or get fancy with your consoles, you often need to specify per-layer information.</p>
<h3><a class="header" href="#building-layers" id="building-layers">Building Layers</a></h3>
<p>You can add as many layers as you want (I haven't tested the upper bound). There are several builder functions that add layers:</p>
<ul>
<li><code>with_simple_console(width, height, font filename)</code> creates a simple console of the specified dimensions, bound to the target font.</li>
<li><code>with_simple_console_no_bg(width, height, font filename)</code> creates a simple console with no background - it won't overwrite underlying layers. This is useful when you want to layer printed data on top of other layers, but still want a simple console.</li>
<li><code>with_simple_8x8</code> creates a simple console bound to the internal 8x8 font, using dimensions that were specified with <code>with_dimensions</code>. This is mostly provided for compatibility with previous versions.</li>
<li><code>with_sparse_console(width, height, font filename)</code> creates a sparse console with the specified dimensions and font.</li>
<li><code>with_sparse_console_no_bg(width, height, font filename)</code> creates a sparse console with the specified dimensions and font. It also sets the &quot;no background&quot; flag, so backgrounds won't be rendered for characters. Instead of blanking the area around a rendered character, it will just render the character data.</li>
<li><code>with_fancy_console(width, height, font filename)</code> creates a fancy console. These will have their own section in the manual.</li>
<li><code>with_sprite_console(width, height, sprite_sheet)</code> creates a sprite console. These will also have their own section in the manual.</li>
</ul>
<p>You can combine these with various <code>with_tile_dimensions</code> and <code>with_dimensions</code> calls. These calls apply to the most recently added layer, allowing you to customize how they are rendered.</p>
<p>For example, this creates an 80x50 layer (0) in 8x8 mode, and an 80x25 layer (1) in VGA font (8x16):</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let context = BTermBuilder::simple80x50()
    .with_font(&quot;vga8x16.png&quot;, 8u32, 16u32)
    .with_sparse_console(80u32, 25u32, &quot;vga8x16.png&quot;)
    .with_title(&quot;Bracket Terminal - Sparse Consoles&quot;)
    .build()?;
<span class="boring">}
</span></code></pre></pre>
<p>A more complicated example (from the Roguelike Tutorial):</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>let mut context = RltkBuilder::simple(80, 60)
    .unwrap()
    .with_title(&quot;Roguelike Tutorial&quot;)
    .with_font(&quot;vga8x16.png&quot;, 8, 16)
    .with_sparse_console(80, 30, &quot;vga8x16.png&quot;)
    .with_vsync(false)
    .build()?;
<span class="boring">}
</span></code></pre></pre>
<p>Note that <code>RltkBuilder</code> is the same as <code>BTermBuilder</code>---it changes its name if you use the library as <code>RLTK</code>. This creates an 80x60 simple console, and then registers a VGA-mode 80x30 (half the height) sparse console.</p>
<p>Another example, this from from <a href="https://hands-on-rust.com/">Hands-on Rust</a>:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>    let context = BTermBuilder::new()
        .with_title(&quot;Dungeon Crawler&quot;)
        .with_fps_cap(30.0)
        .with_dimensions(DISPLAY_WIDTH, DISPLAY_HEIGHT)
        .with_tile_dimensions(32, 32)
        .with_resource_path(&quot;resources/&quot;)
        .with_font(&quot;dungeonfont.png&quot;, 32, 32)
        .with_font(&quot;terminal8x8.png&quot;, 8, 8)
        .with_simple_console(DISPLAY_WIDTH, DISPLAY_HEIGHT, &quot;dungeonfont.png&quot;)
        .with_simple_console_no_bg(DISPLAY_WIDTH, DISPLAY_HEIGHT, &quot;dungeonfont.png&quot;)
        .with_simple_console_no_bg(SCREEN_WIDTH*2, SCREEN_HEIGHT*2, &quot;terminal8x8.png&quot;)
<span class="boring">}
</span></code></pre></pre>
<p>This sets a window title and an FPS cap. Then it sets the window size and tile dimensions, and a resource path. It loads the two fonts, and sets up three layers: a simple console for the map, a simple console for characters, and a text layer over the top.</p>
<h3><a class="header" href="#constructing-your-session" id="constructing-your-session">Constructing Your Session</a></h3>
<p>Once you're done with specifying details, you finish the builder chain with <code>.build()</code>. It returns a <code>Result</code> type, so it's handy to use the <code>?</code> syntax---but you can handle errors however you wish. Sometimes, you asked for the impossible---or the underlying system just won't cooperate with your wishes. These generate errors. Otherwise, you receive a usable context---which you can run with the <code>main_loop</code> function and your game state (see below).</p>
<h2><a class="header" href="#handing-over-control" id="handing-over-control">Handing Over Control</a></h2>
<p><code>Bracket-terminal</code> takes over control of the main game loop. It does this because it needs to continually interact with your operating system (or browser in WASM mode), marshall events and handle redrawing the screen. You need to create a <code>State</code> object that <em>must</em> implement <code>GameState</code>---and begin execution with <code>main_loop(my_state)</code>.</p>
<p>For example, the following from &quot;hello terminal&quot; hands over control:</p>
<pre><pre class="playground"><code class="language-rust">use bracket_lib::prelude::*;

struct State {}

impl GameState for State {
    fn tick(&amp;mut self, ctx: &amp;mut BTerm) {
        ctx.print(1, 1, &quot;Hello Bracket World&quot;);
    }
}

fn main() -&gt; BError {
    let context = BTermBuilder::simple80x50()
        .with_title(&quot;Hello Minimal Bracket World&quot;)
        .build()?;

    let gs: State = State {};
    main_loop(context, gs)
}
</code></pre></pre>
<p>The <code>tick</code> function in your <code>GameState</code> implementing structure is called every frame.</p>
<h1><a class="header" href="#printing-to-consoles" id="printing-to-consoles">Printing to Consoles</a></h1>
<p>Probably the most common thing to do with a console is to print text to it. This can be actual text, or characters mapped to sprites in your font file---but it's a <em>really</em> common task. <code>Bracket-terminal</code> provides a lot of different ways to do this.</p>
<h2><a class="header" href="#interacting-with-your-context" id="interacting-with-your-context">Interacting with Your Context</a></h2>
<p>Your <code>tick</code> function receives a <code>ctx: &amp;mut BTerm</code> parameter. This provides a link between your program and the terminals. Almost all of the direct control functions are called as methods on the <code>ctx</code>. You'll need to pass your context (or parts of it) to child functions in your program. This allows your program to control the console, while the library retains overall control of execution.</p>
<blockquote>
<p>Passing a mutable reference around can be a pain. That's why there are other options, which will be covered later.</p>
</blockquote>
<h2><a class="header" href="#working-with-layers" id="working-with-layers">Working with Layers</a></h2>
<p>If you have multiple layers, you need to make sure that you call <code>ctx.set_active_console(index)</code> to activate the one you wish to target. Most draw commands are passed through to the underlying console---the library needs to know where to send them. It's a good idea to remember to call <code>set_active_console(0)</code> at the end of your session, to ensure you don't forget to change back to the default on another pass.</p>
<h2><a class="header" href="#direct-drawing-commands" id="direct-drawing-commands">Direct Drawing Commands</a></h2>
<p>There are <em>many</em> different options for drawing to the console.</p>
<h3><a class="header" href="#clearing-the-screen" id="clearing-the-screen">Clearing the Screen</a></h3>
<p>You have two options for clearing a console: <code>ctx.cls()</code> clears the screen to a black background, <code>ctx.cls_bg(color)</code> clears the console to a specified background color (and has no effect on layers without background).</p>
<p>You often want to clear the console at the start of a tick, if you plan to draw the whole screen. Some optimizations may occur that make it <em>not really</em> clear and redraw everything, especially in Curses and Crossterm modes.</p>
<h3><a class="header" href="#specifying-characters" id="specifying-characters">Specifying Characters</a></h3>
<p>Characters need to be selected from the <code>codepage-437</code> list. There's a <a href="https://dwarffortresswiki.org/index.php/Character_table">great chart</a> showing CP-437 here.</p>
<p>You can convert a Rust character into a codepage-437 character with <code>to_cp437('X')</code>.</p>
<h3><a class="header" href="#printing-a-single-characterglyph" id="printing-a-single-characterglyph">Printing a Single Character/Glyph</a></h3>
<p>You can print a single CP-437 character with the <code>ctx.set(x, y, foreground, background, glyph)</code> command. This is mostly used by the <code>print</code> commands, but you can use it yourself if you wish.</p>
<p>For example:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>ctx.set(1, 1, RED.into(), BLACK.into(), to_cp437('☺'));
<span class="boring">}
</span></code></pre></pre>
<p>This will set the character at 1,1 (near the top-left) to a red smiley face with a black background.</p>
<p>You can also use <code>ctx.set_bg(x, y, color)</code> to set just the background color a cell.</p>
<h3><a class="header" href="#printing-strings" id="printing-strings">Printing Strings</a></h3>
<p>You can print a string with the <code>ctx.print(x, y, string)</code> function. You don't need to convert the characters in the string---the library does it for you. No color is specified, it will just use black/white.</p>
<p>If you'd like to print in color, <code>ctx.print_color(x, y, foreground, background, string)</code> works the same way---but specifies the colors to use.</p>
<p>You can center your text (horizontally) around a given <code>y</code> coordinate with <code>print_centered(y, string)</code> and <code>print_color_centered(y, fg, bg, string)</code>. These center relative to the whole panel.</p>
<p>You can also center your text around a specific point with <code>print_centered_at(x, y, text)</code> and its friend <code>print_color_centered_at(x, y, fg, bg, string)</code>.</p>
<p>You can right-justify your text with <code>print_color_right(x, y, fg, bg, string)</code> and <code>print_right(x, y, string)</code>.</p>
<p>I didn't want to tackle full-justification. Hyphenation systems are painful.</p>
<h3><a class="header" href="#printing-with-more-control" id="printing-with-more-control">Printing with More Control</a></h3>
<p>If you need to do fancy things like having different words in different colors, you can use the <code>ctx.printer</code> system:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>printer(x, y, string, alignment, background)
<span class="boring">}
</span></code></pre></pre>
<ul>
<li>The <code>x</code> and <code>y</code> coordinates behave as you'd expect.</li>
<li><code>alignment</code> takes a <code>TextAlign</code> enum: <code>TextAlign::Left</code>, <code>TextAlign::Center</code> or <code>TextAlign::Right</code>.</li>
<li><code>background</code> is an <code>Option</code>. So either specify <code>None</code> (for no background), or <code>Some(color)</code>.</li>
</ul>
<p>Text in the printer accepts control characters to specify colors. You have to register these with calls to <code>register_palette_color</code> (typically in your main function. It's a free function, not attached to your context). You can then use control characters inside your string. They are a <em>stack</em>---so you have to exit out once you are done with formatting.</p>
<p>For example:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>register_palette_color(&quot;blue&quot;, RGB::named(BLUE));
register_palette_color(&quot;pink&quot;, RGB::named(MAGENTA));
<span class="boring">}
</span></code></pre></pre>
<p>This code assigns the name &quot;blue&quot; and &quot;pink&quot; to appropriate RGB colors. In your <code>tick</code> function, you can then use <code>printer</code> as follows:</p>
<pre><pre class="playground"><code class="language-rust">
<span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>ctx.printer(
    40,
    49,
    &quot;#[blue]Hello #[pink]Bracket#[] world.&quot;,
    TextAlign::Center,
    Some(RGBA::from_u8(200, 200, 200, 255)),
);
<span class="boring">}
</span></code></pre></pre>
<p>Notice that <code>#[]</code> is used to end the color. This will print &quot;Hello&quot; and &quot;world&quot; in blue, and &quot;Bracket&quot; in pink. The <code>#[]</code> has popped the stack---reverting to the <em>previously specified</em> color.</p>
<h3><a class="header" href="#drawing-boxes" id="drawing-boxes">Drawing Boxes</a></h3>
<p>You can use the <code>ctx.draw_box(x, y, width, height, foreground, background)</code> function to draw a single-lined box at the specified coordinates.</p>
<p>Likewise, <code>ctx.draw_box_double(x, y, w, h, fg, bg)</code> does the same thing---but with double-lines.</p>
<p>Both of these functions zero out the contents of the box. If you don't want to do that, <code>draw_hollow_box</code> and <code>draw_hollow_box_double</code> omit this step, but otherwise operate in the same way.</p>
<h3><a class="header" href="#drawing-progressscrollhealth-bars" id="drawing-progressscrollhealth-bars">Drawing Progress/Scroll/Health Bars</a></h3>
<p>The function <code>ctx.draw_bar_horizontal</code> renders a bar, with a specified percentage in one color and a percentage in another. The full syntax is:</p>
<pre><code>draw_bar_horizontal(x, y, width, number, max, foreground, background)
</code></pre>
<p>Specify <code>number</code> as the current number, bounded by <code>max</code>. For example, a health bar showing 6 out of 12 possible hit points remaining would use a <code>number</code> of <code>6</code> and <code> max</code> of 12.</p>
<p>If you'd like to do the same thing, but with a vertical bar you can use:</p>
<pre><code>draw_bar_vertical(x, y, height, number, max, foreground, background)
</code></pre>
<h3><a class="header" href="#filling-a-region" id="filling-a-region">Filling a Region</a></h3>
<p>You can fill a rectangular region of the screen with the <code>ctx.fill_region(target, symbol, foreground, background)</code> function. <code>target</code> is a <code>Rect</code> from <code>bracket-geometry</code>.</p>
<h1><a class="header" href="#other-console-options" id="other-console-options">Other Console Options</a></h1>
<p>There are a bunch of other console-related functions.</p>
<h2><a class="header" href="#controlling-string-translation" id="controlling-string-translation">Controlling String Translation</a></h2>
<p>You can change the console's translation mode with <code>set_translation_mode</code>. By default, all strings are turned into <code>cp437</code>. If you are using a big unicode font, you can change to <code>CharacterTranslationMode::Unicode</code> to support it. See the <code>unicode</code> example for details.</p>
<h2><a class="header" href="#clipping-rendering" id="clipping-rendering">Clipping Rendering</a></h2>
<p>If you only want your rendering to apply to a given region of the screen, you can call <code>ctx.set_clipping(Some(Rect))</code> (and remove it with <code>ctx.set_clipping(None)</code>). Rendered characters will only appear if they are within the clipping region. This can be handy for limiting window rendering.</p>
<h2><a class="header" href="#changing-font" id="changing-font">Changing Font</a></h2>
<p>You can change a console to use any registered font on the fly with <code>ctx.set_active_font(font index, bool)</code>. If the bool is true, the console will resize to the dimensions implied by the font size. The &quot;font index&quot; is the order in which the font was inserted.</p>
<p>You can override the internal size of a font with <code>ctx.set_char_size</code>. Use this with caution. A better approach to resizing is to call <code>ctx.set_char_size_and_resize_window(width, height)</code>. This doesn't work on all platforms.</p>
<h2><a class="header" href="#changing-alpha" id="changing-alpha">Changing Alpha</a></h2>
<p>You can change the alpha-level of ALL characters on a layer with <code>set_all_fg_alpha</code> and <code>set_all_bg_alpha</code>. The <code>set_all_alpha</code> applies your change to both foregrounds and backgrounds.</p>
<h2><a class="header" href="#scaling-the-console" id="scaling-the-console">Scaling the Console</a></h2>
<p>You can set a console scale with <code>set_scale</code> (and query it with <code>get_scale</code>). This allows you to &quot;zoom in&quot; on a layer. It's not commonly used.</p>
<h2><a class="header" href="#saving-a-console" id="saving-a-console">Saving a Console</a></h2>
<p>You can save the current state of a console to a REX Paint file by calling <code>to_xp_layer</code>. You can take a <code>PNG</code> screenshot with <code>ctx.screenshot(filename)</code>.</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                        

                        

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                

                
            </nav>

        </div>

        

        

        

        
        <script type="text/javascript">
            window.playground_copyable = true;
        </script>
        

        

        
        <script src="elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="searcher.js" type="text/javascript" charset="utf-8"></script>
        

        <script src="clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->
        

        
        
        <script type="text/javascript">
        window.addEventListener('load', function() {
            window.setTimeout(window.print, 100);
        });
        </script>
        
        

    </body>
</html>
